<template>
  <div class="pagination" v-if="totalPages > 1">
    <button class="page-item" :disabled="currentPage === 1" @click="goToPage(currentPage - 1)">
      上一页
    </button>
    <button
        v-for="page in pages"
        :key="page"
        class="page-item"
        :class="{ active: page === currentPage, dots: page === '...' }"
        :disabled="page === '...'"
        @click="goToPage(page)"
    >
      {{ page }}
    </button>
    <button class="page-item" :disabled="currentPage === totalPages" @click="goToPage(currentPage + 1)">
      下一页
    </button>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, computed } from 'vue';

const props = defineProps({
  currentPage: {
    type: Number,
    required: true,
  },
  totalPages: {
    type: Number,
    required: true,
  },
  maxVisibleButtons: {
    type: Number,
    default: 5,
  },
});

const emit = defineEmits(['page-changed']);

const pages = computed(() => {
  const range = [];
  const total = props.totalPages;
  const current = props.currentPage;
  const max = props.maxVisibleButtons;

  if (total <= max) {
    for (let i = 1; i <= total; i++) {
      range.push(i);
    }
    return range;
  }

  range.push(1);

  let start = Math.max(2, current - Math.floor((max - 3) / 2));
  let end = Math.min(total - 1, start + max - 3);

  if (end - start < max - 3) {
    start = end - max + 3;
  }

  if (start > 2) {
    range.push('...');
  }

  for (let i = start; i <= end; i++) {
    range.push(i);
  }

  if (end < total - 1) {
    range.push('...');
  }

  range.push(total);

  return range;
});

const goToPage = (page) => {
  if (page !== '...' && page >= 1 && page <= props.totalPages) {
    emit('page-changed', page);
  }
};
</script>

<style scoped>
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 25px;
  gap: 8px;
}

.page-item {
  padding: 8px 14px;
  border: 1px solid #ddd;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  background-color: white;
  transition: all 0.3s;
}

.page-item:hover:not(:disabled):not(.active) {
  background: #f0f4f8;
  border-color: #cdd4db;
}

/* 选中项使用原有的蓝色，代表专业和可靠 */
.page-item.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
  font-weight: bold;
}

.page-item:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.page-item.dots {
  border: none;
  background: transparent;
}
</style>